package com.tuanzi.loan.schedule.receipt;

import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.receipt.product.ReceiptProductInfo;
import com.tuanzi.loan.business.entity.receipt.statistics.ReceiptRechargeOrder;
import com.tuanzi.loan.business.entity.receipt.statistics.ReceiptRechargeStatistics;
import com.tuanzi.loan.business.entity.receipt.user.ReceiptSystemUser;
import com.tuanzi.loan.business.service.receipt.product.ReceiptProductInfoService;
import com.tuanzi.loan.business.service.receipt.statistics.ReceiptBalanceOperationRecordService;
import com.tuanzi.loan.business.service.receipt.statistics.ReceiptRechargeOrderService;
import com.tuanzi.loan.business.service.receipt.statistics.ReceiptRechargeStatisticsService;
import com.tuanzi.loan.business.service.receipt.user.ReceiptSystemUserService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.receipt.statistics.ReceiptBalanceOperationRecordView;
import com.tuanzi.server.loan_base.constant.LoanReceiptProductStatus;
import com.tuanzi.server.loan_base.constant.receipt.LoanReceiptRechargeOrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lsx
 */
@Debug
@Slf4j
@Service
@Transactional
public class StatisticsReceiptRechargeScheduler {

    @Autowired
    private ReceiptRechargeOrderService receiptRechargeOrderService;

    @Autowired
    private ReceiptRechargeStatisticsService receiptRechargeRecordService;

    @Autowired
    private ReceiptSystemUserService receiptSystemUserService;

    @Autowired
    private ReceiptProductInfoService receiptProductInfoService;

    @Autowired
    private ReceiptBalanceOperationRecordService balanceOperationRecordService;


    /**
     * 定时统计用户每天的充值记录
     */

    public void insertRechargeRecord() {
        DateTime nowTime = new DateTime(new Date()).plusDays(-1);
        Date startTime = new DateTime(nowTime.getYear(), nowTime.getMonthOfYear(), nowTime.getDayOfMonth(), 0, 0, 0).toDate();
        Date endTime = new DateTime(nowTime.getYear(), nowTime.getMonthOfYear(), nowTime.getDayOfMonth(), 23, 59, 59).toDate();

        List<ReceiptSystemUser> systemUserLists = receiptSystemUserService.findByParentIsNull();
        for(ReceiptSystemUser systemUser : systemUserLists) {
            ReceiptRechargeStatistics rechargeRecord = newRechargeRecord();
            String userId = systemUser.getId();
            List<ReceiptRechargeOrder> loanReceiptRechargeOrderList = receiptRechargeOrderService.findByLoanReceiptSystemUserIdAndCreateTimeBetween(userId, startTime, endTime);
            if (loanReceiptRechargeOrderList.size() > 0) {
                float totalOrderAmount = 0;
                for (ReceiptRechargeOrder loanReceiptRechargeOrder : loanReceiptRechargeOrderList) {
                    if (loanReceiptRechargeOrder.getOrderStatus() == LoanReceiptRechargeOrderStatus.DONE) {
                        totalOrderAmount += loanReceiptRechargeOrder.getOrderAmount();
                    }
                    rechargeRecord.setRechargePrice(totalOrderAmount);
                }
            } else {
                rechargeRecord.setRechargePrice(0f);
            }

            List<LoanReceiptProductStatus> statusList = new ArrayList<>();
            statusList.add(LoanReceiptProductStatus.OFFLINE);
            statusList.add(LoanReceiptProductStatus.ONLINE);
            ReceiptProductInfo productInfo = receiptProductInfoService.findEarliestProductInfoByUserIdAndStatusIn(userId, statusList);
            BigDecimal unitPrice = new BigDecimal(0);
            if (productInfo != null) {
                unitPrice = productInfo.getUnitPrice();
            }
            rechargeRecord.setUnitPrice(unitPrice);
            rechargeRecord.setCountBalance(systemUser.getBalance());
            rechargeRecord.setUserId(userId);
            rechargeRecord.setDate(startTime);
            ReceiptBalanceOperationRecordView loanReceiptBalanceOperationRecordView = balanceOperationRecordService.findRecordResponseByUserId(userId, startTime, endTime);
            if (loanReceiptBalanceOperationRecordView.getConsumePrice() != null) {
                rechargeRecord.setConsumePrice(-loanReceiptBalanceOperationRecordView.getConsumePrice());
            }
            rechargeRecord.setDeliveryCount(loanReceiptBalanceOperationRecordView.getDeliveryCount());
            receiptRechargeRecordService.saveOrUpdate(rechargeRecord);
        }
    }

    private ReceiptRechargeStatistics newRechargeRecord() {
        ReceiptRechargeStatistics rechargeRecord = new ReceiptRechargeStatistics();
        rechargeRecord.setUnitPrice(new BigDecimal(0));
        rechargeRecord.setCountBalance(new BigDecimal(0));
        rechargeRecord.setConsumePrice(0f);
        rechargeRecord.setCountBalance(new BigDecimal(0));
        rechargeRecord.setRechargePrice(0f);
        return rechargeRecord;
    }

//    @Scheduled(cron = "${cron.statistics.recharge-order}")
    public void insertRechargeRecordNew() {
        LogService.info("甲方每日统计开始");
        DateTime nowTime = new DateTime(new Date()).plusDays(-1);
        Date startTime = new DateTime(nowTime.getYear(), nowTime.getMonthOfYear(), nowTime.getDayOfMonth(), 0, 0, 0).toDate();
        Date endTime = new DateTime(nowTime.getYear(), nowTime.getMonthOfYear(), nowTime.getDayOfMonth(), 23, 59, 59).toDate();
        List<ReceiptSystemUser> systemUserLists = receiptSystemUserService.findByParentIsNull();
        for (ReceiptSystemUser systemUser : systemUserLists) {
            ReceiptRechargeStatistics rechargeRecord = newRechargeRecord();
            String userId = systemUser.getId();
            List<ReceiptRechargeOrder> loanReceiptRechargeOrderList = receiptRechargeOrderService
                    .findReceiptRechargeOrdersByLoanReceiptSystemUserIdAndPayTimeBetweenWhereIsDone(userId, startTime, endTime);
            if (loanReceiptRechargeOrderList !=null && loanReceiptRechargeOrderList.size() > 0) {
                Double amount = loanReceiptRechargeOrderList.parallelStream().mapToDouble(order -> order.getOrderAmount()).sum();
                rechargeRecord.setRechargePrice(amount.floatValue()); //充值记录
            }

            List<LoanReceiptProductStatus> statusList = new ArrayList<>();
            statusList.add(LoanReceiptProductStatus.OFFLINE);
            statusList.add(LoanReceiptProductStatus.ONLINE);
            ReceiptProductInfo productInfo = receiptProductInfoService.findEarliestProductInfoByUserIdAndStatusIn(userId, statusList);
            BigDecimal unitPrice = new BigDecimal(0);
            if (productInfo != null) {
                unitPrice = productInfo.getUnitPrice();
            }
            rechargeRecord.setUnitPrice(unitPrice); //单价
            rechargeRecord.setCountBalance(systemUser.getBalance()); //账号余额
            rechargeRecord.setUserId(userId); //借条主账号id
            rechargeRecord.setDate(startTime); //时间

            List<ReceiptRechargeStatistics> rechargeRecordList = Lists.newArrayList();
            List<ReceiptBalanceOperationRecordView> balanceOperationList = balanceOperationRecordService.findRecordResponseSourceFromByUserId(userId, startTime, endTime);
            if (balanceOperationList != null && balanceOperationList.size() > 0) {
                int count = 0;
                for (ReceiptBalanceOperationRecordView view : balanceOperationList) {
                    ReceiptRechargeStatistics receiptRechargeStatistics = newRechargeRecord();
                    BeanUtils.copyProperties(rechargeRecord, receiptRechargeStatistics);
                    //防止最新单价、充值、账号余额重复，我们只去第一次，其余都设置为0,已产品为单位
                    if(count != 0){
                        receiptRechargeStatistics.setCountBalance(new BigDecimal(0)); //账户余额
                        receiptRechargeStatistics.setRechargePrice(0F); //充值记录
                        receiptRechargeStatistics.setUnitPrice(new BigDecimal(0)); //单价
                    }

                    receiptRechargeStatistics.setConsumePrice(-view.getConsumePrice());// 消耗（元）
                    receiptRechargeStatistics.setDeliveryCount(view.getDeliveryCount()); // 投递数
                    receiptRechargeStatistics.setSourceFrom(view.getSourceFrom()); // 来源
                    rechargeRecordList.add(receiptRechargeStatistics);
                    count ++;
                }
                receiptRechargeRecordService.saveOrUpdate(rechargeRecordList);
            }
        }
        LogService.info("甲方每日统计结束");
    }

}
